#ifdef WX_PRECOMP
    #include "wx_pch.h"
#else
    #include <wx/datetime.h>
#endif
    #include <wx/file.h>
    #include <wx/filename.h>
    #include <wx/dnd.h>

//-#if defined(BUILDING_PLUGIN)
    #include "sdk.h"

#include "codesnippetswindow.h"
#include "snippetitemdata.h"
#include "menuidentifiers.h"
#include "GenericMessageBox.h"
#include "snippetsconfig.h"
#include "snippetproperty.h"

#include "version.h"
#include <wx/wxscintilla.h>                        

   BEGIN_EVENT_TABLE(SnippetProperty, SnippetPropertyForm)
    EVT_BUTTON(wxID_OK,             SnippetProperty::OnOk)
    EVT_BUTTON(wxID_CANCEL,         SnippetProperty::OnCancel)
    EVT_BUTTON(ID_SNIPPETBUTTON,    SnippetProperty::OnSnippetButton)
    EVT_BUTTON(ID_FILESELECTBUTTON, SnippetProperty::OnFileSelectButton)
   

   END_EVENT_TABLE()

class SnippetDropTarget : public wxTextDropTarget
{
   

	public:
		SnippetDropTarget(SnippetProperty* window) : m_Window(window) {}
		~SnippetDropTarget() {}
		bool OnDropText(wxCoord x, wxCoord y, const wxString& data);
	private:
		SnippetProperty* m_Window;
};

bool SnippetDropTarget::OnDropText(wxCoord x, wxCoord y, const wxString& data) {
   
    #ifdef LOGGING
     LOGIT( _T("Dragged Data[%s]"), data.GetData() );
    #endif
   
    m_Window->m_SnippetEditCtrl->AddText(data);
    return true;

}


SnippetProperty::SnippetProperty(wxTreeCtrl* pTree, wxTreeItemId itemId, wxSemaphore* pWaitSem)
    :SnippetPropertyForm(pTree->GetParent(),-1,wxT("Snippet Properties")) {
    InitSnippetProperty( pTree, itemId, pWaitSem );
}

void SnippetProperty::InitSnippetProperty(wxTreeCtrl* pTree, wxTreeItemId itemId, wxSemaphore* pWaitSem) {
   

   

    m_pWaitingSemaphore = pWaitSem;
    m_nScrollWidthMax = 0;
   
    wxPoint mousePosn = ::wxGetMousePosition();
    this->Move(mousePosn.x, mousePosn.y);
    this->SetSize(mousePosn.x, mousePosn.y, 460, 260);
   
    GetConfig()->CenterChildOnParent(this);

    m_pTreeCtrl = pTree;
    m_TreeItemId = itemId;

   
    m_ItemLabelTextCtrl->SetValue( pTree->GetItemText(itemId) );
    m_ItemLabelTextCtrl->Connect(wxEVT_COMMAND_TEXT_ENTER,
        wxCommandEventHandler( SnippetProperty::OnOk ), NULL, this );

    m_SnippetEditCtrl->SetText( wxT("Enter text or Filename") );
    m_SnippetEditCtrl->SetFocus();

	wxColour txtBackground = m_ItemLabelTextCtrl->GetBackgroundColour();
   
    m_SnippetEditCtrl->StyleSetBackground (wxSCI_STYLE_DEFAULT, txtBackground);
    m_SnippetEditCtrl->StyleClearAll();


	if (( m_pSnippetDataItem = (SnippetTreeItemData*)(pTree->GetItemData(itemId))))
	{
	
		if (m_pSnippetDataItem->GetType() != SnippetTreeItemData::TYPE_SNIPPET)
		{
		   
		   

			return;
		}

        wxString snippetText = m_pSnippetDataItem->GetSnippetString() ;
        if ( not snippetText.IsEmpty() )
        {
            GetSnippetEditCtrl()-> SetText( snippetText );
            GetSnippetEditCtrl()->SetSavePoint();
           
           
           
           
           
           
           
           
            m_SnippetEditCtrl->EmptyUndoBuffer();
        }

       
       
       

	}
	SetDropTarget(new SnippetDropTarget(this));

}

SnippetProperty::~SnippetProperty() {
   
}

void SnippetProperty::OnOk(wxCommandEvent& event) {
     LOGIT( _T("SnippetProperty::OnOK") );
   
    m_pSnippetDataItem->SetSnippetString( m_SnippetEditCtrl->GetText() );
   
    m_pTreeCtrl->SetItemText( m_TreeItemId, m_ItemLabelTextCtrl->GetValue() );
    if (m_pWaitingSemaphore) m_pWaitingSemaphore->Post();
    this->EndModal(wxID_OK);
}

void SnippetProperty::OnCancel(wxCommandEvent& event) {
     LOGIT( _T("SnippetProperty::OnCancel") );
    if (m_pWaitingSemaphore) m_pWaitingSemaphore->Post();
    this->EndModal(wxID_CANCEL);
}

void SnippetProperty::OnSnippetButton(wxCommandEvent& event) {
   

    if ( GetActiveMenuId() == idMnuConvertToFileLink )
    {      
        wxString ChosenFileName = wxFileSelector(wxT("Choose a Link target"));
        if (not ChosenFileName.IsEmpty())
            m_SnippetEditCtrl-> SetText( ChosenFileName );
        return;
    }

   
    if ( ( g_activeMenuId == idMnuProperties )
       
       
       
       
        )
    {
        if ( GetConfig()->SettingsExternalEditor.IsEmpty())
        {   GenericMessageBox(wxT("Use Menu/Settings/Options to specify an external editor.") );
            return;
        }
           
           
           
           
        if ( IsSnippetFile() )
             InvokeEditOnSnippetFile();
        else InvokeEditOnSnippetText();

    }//fi
    return;
}

void SnippetProperty::OnFileSelectButton(wxCommandEvent& event) {
   

   
    wxString ChosenFileName = wxFileSelector(wxT("Choose a file"));
    if (not ChosenFileName.IsEmpty())
        m_SnippetEditCtrl-> SetText( ChosenFileName );
    return;

}

void SnippetProperty::InvokeEditOnSnippetText() {
       

        wxFileName tmpFileName = wxFileName::CreateTempFileName(wxEmptyString);
        #ifdef LOGGING
         LOGIT( _T("fakename:[%s]"),tmpFileName.GetFullPath().GetData() );
        #endif

        wxFile tmpFile( tmpFileName.GetFullPath(), wxFile::write);
        if (not tmpFile.IsOpened() )
        {
           
            GenericMessageBox(wxT("Open failed for:")+tmpFileName.GetFullPath());
            return ;
        }
        wxString snippetData( GetSnippetString() );
        tmpFile.Write( csU2C(snippetData), snippetData.Length());
        tmpFile.Close();
           
           
        wxString externalEditor = GetConfig()->SettingsExternalEditor;
        if ( externalEditor == _T("Enter filename of external editor") )
        {   GenericMessageBox(wxT("No external editor specified.\n Check settings.\n"));
            return;
        }
        wxString execString = GetConfig()->SettingsExternalEditor + wxT(" \"") + tmpFileName.GetFullPath() + wxT("\"");

        #ifdef LOGGING
         LOGIT( _T("Properties wxExecute[%s]"), execString.GetData() );
        #endif

           
        ::wxExecute( execString, wxEXEC_SYNC);
           
        tmpFile.Open(tmpFileName.GetFullPath(), wxFile::read);
        if (not tmpFile.IsOpened() )
        {   GenericMessageBox(wxT("Abort.Error reading temp data file."));
            return;
        }
        unsigned long fileSize = tmpFile.Length();

        #ifdef LOGGING
         LOGIT( _T("New file length[%d]"),fileSize );
        #endif

           
        char pBuf[fileSize+1];
        size_t nResult = tmpFile.Read( pBuf, fileSize );
        if ( wxInvalidOffset == (int)nResult )
            GenericMessageBox(wxT("InvokeEditOnSnippetText()\nError reading temp file"));
        pBuf[fileSize] = 0;
        tmpFile.Close();

        #ifdef LOGGING
         
        #endif

           
        snippetData = csC2U( pBuf );

         #ifdef LOGGING
         
         #endif

           
        ::wxRemoveFile( tmpFileName.GetFullPath() );

           
        m_SnippetEditCtrl-> SetText( snippetData );
}

void SnippetProperty::InvokeEditOnSnippetFile() {
   

    if (not IsSnippetFile() ) return;


    wxString FileName = GetConfig()->GetSnippetsTreeCtrl()->GetSnippetFileLink();

   
    wxString pgmName = GetConfig()->SettingsExternalEditor;
    if ( pgmName.IsEmpty() )
    {
        #if defined(__WXMSW__)
                pgmName = wxT("notepad");
        #elif defined(__UNIX__)
                pgmName = wxT("gedit");
        #endif
    }

   
	wxString execString = pgmName + wxT(" \"") + FileName + wxT("\"");
    #ifdef LOGGING
     LOGIT( _T("InvokeEditOnSnippetFile[%s]"), execString.GetData() );
    #endif
    ::wxExecute( execString);
    return;
}
